package com.sp.homework;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * 客户端
 */
public class Homework03Client {
    public static void main(String[] args) throws Exception {

        //1. 接收用户输入, 指定下载文件名
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入下载文件名");
        String downloadFileName = scanner.next();

        //2. 客户端连接服务端, 准备发送
        Socket socket = new Socket(InetAddress.getLocalHost(),9999);

        //3. 获取和Scoket关联的输出流
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(downloadFileName.getBytes());
        //设置写入结束的标志
        socket.shutdownOutput();

        //4. 读取服务端返回的文件
        BufferedInputStream bufferedInputStream = new BufferedInputStream(socket.getInputStream());
        byte[] bytes = StreamUtils.streamToByteArray(bufferedInputStream);

        //5. 得到一个输出流, 将bytes写入到磁盘文件
        String filePath = "d:\\development\\code\\IO_Test\\news\\2.mp3";
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(filePath));
        bufferedOutputStream.write(bytes);

        //6. 关闭相关的资源
        bufferedOutputStream.close();
        bufferedInputStream.close();
        outputStream.close();
        socket.close();

        System.out.println("客户端下载完毕, 正在退出");

    }
}
